Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add distinct method to FakeQuerySet #188

Closed
wants to merge 2 commits into from

Conversation

KIRA009
Copy link
Contributor

@KIRA009 KIRA009 commented Feb 21, 2024

Fixes #29

This PR adds the distinct method to the FakeQuerySet class. It mimics the behavior of django's distinct method - calls to distinct with a list of field names, are only allowed if the db connection vendor is postgresql.


def distinct(self, *fields):
if fields and connection.vendor != 'postgresql':
raise NotSupportedError("DISTINCT ON fields is not supported by this database backend")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed, given that we're bypassing the database here? I guess you're trying to keep FakeQuerySet as close as possible to the real database behaviour, but I think it's fine for FakeQuerySet to have extra functionality that the database doesn't support.

fields = [field.name for field in self.model._meta.fields if not field.primary_key]
seen_keys = set()
for result in self.results:
key = '$$$'.join([str(extract_field_value(result, field)) for field in fields])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest using a tuple here - unlike lists, they're valid to use as keys within a set:

Suggested change
key = '$$$'.join([str(extract_field_value(result, field)) for field in fields])
key = tuple(str(extract_field_value(result, field)) for field in fields)

gasman pushed a commit that referenced this pull request Feb 23, 2024
@gasman
Copy link
Contributor

gasman commented Feb 23, 2024

Merged in a8d4b9a - thanks @KIRA009!

@gasman gasman closed this Feb 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement QuerySet.distinct in FakeQuerySet
2 participants